package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.tianxin.workbao.workBao.bean.LoaderUse;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.SPUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by hacker on 2017/7/1.
 */

public class LoaderUseProvide extends BaseDataProvide {

    private Context mContext;
    private Handler saveDbHandler;
    private List<LoaderUse> loaderUseList;
    private UpdateListViewListener mListener;
    private int mPage=1;

    public LoaderUseProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mContext = context;
        mListener = listener;
        saveDbHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                handlerData(msg.obj);
            }
        };
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mListener.hideProgress();
                    handlerData(responseObj);
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mListener.hideProgress();
                    showRequestErrorMessage(mListener,reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    /**
     * 数据
     *
     * @param obj 请求返回的所有内容
     */
    private void handlerData(Object obj) {
        try {
            JSONObject jsonObject = new JSONObject(obj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                String data = jsonObject.getString(Constant.RESPONSE_DATA);
                if (data.startsWith("[") && data.endsWith("]")) {
                    JSONArray array = jsonObject.getJSONArray(Constant.RESPONSE_DATA);
                    if (array.length() > 0) {
                        loaderUseList = BeansUtil.loaderUseToBeans(data);
                        refreshUI();
                    } else {
                        Log.d(Constant.COM_TAG, "response : data is empty !" + obj.toString());
                    }
                }
            } else {
                Log.d(Constant.COM_TAG, "response : no data !" + obj.toString());
            }
        }  catch (Exception e) {
            showRequestErrorMessage(mListener,obj.toString());
            e.printStackTrace();
        }
    }

    public List<LoaderUse> getLoaderUseList() {
        if (loaderUseList == null) {
            loaderUseList = new ArrayList<>();
        }
        updateFromServer();
        return loaderUseList;
    }

    /**
     * update the use Information of the loader
     */
    private void updateFromServer() {
        mListener.showProgress();
        String loaderUseUrl = URL.getLoaderUseUrl();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        RequestParams params = new RequestParams(map);
        Request request = CommonRequest.createPostRequest(loaderUseUrl, params);
        CommonOkHttpClient.post(request, getDisposeDataHandle());
    }


    /**
     * 获取当前用户正在使用的装载机
     *
     * @param userId
     * @return
     */
    public void getCurrUseLoader(int userId) {
        if (userId == 0) {
            return;
        }
        final LoaderUse[] loaderUse = {null};
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("userid", userId + "");
        RequestParams params = new RequestParams(map);
        Request request = CommonRequest.createPostRequest(URL.getCurrUseLoaderUrl(), params);
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                try {
                    JSONObject jsonObject = new JSONObject(responseObj.toString());
                    int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
                    if (status == 1) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject(Constant.RESPONSE_DATA);
                        loaderUse[0] = BeansUtil.loaderUseToBean(jsonObject1.toString());
                        mListener.onRefreshData(loaderUse[0]);
                    }
                } catch (Exception e) {
                    showRequestErrorMessage(mListener,responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mListener.hideProgress();
                showRequestErrorMessage(mListener,reasonObj.toString());
            }
        }));
    }

    /**
     * use loader 占用装载机，
     *
     * @param loaderId
     * @return
     */
    public void useLoader(Integer loaderId) {
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME,getAppToken());
        map.put("userid", SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0) + "");
        map.put("loaderid", loaderId + "");
        RequestParams params = new RequestParams(map);
        Request request = CommonRequest.createPostRequest(URL.getUseLoaderUrl(), params);
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                try {
                    JSONObject jsonObject = new JSONObject(responseObj.toString());
                    int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
                    if (status == 1) {
                        mListener.onRefreshData(1);
                    }
                } catch (JSONException e) {
                    Log.d(TAG, "Json error" + responseObj.toString());
                    e.printStackTrace();
                } catch (Exception e) {
                    Log.d(TAG, "Json to bean error");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                Log.d(TAG, "no use loader");
            }
        }));

    }

    public void giveUpUseLoader(Integer loaderId) {
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME,getAppToken());
        map.put("userid", SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0) + "");
        map.put("loaderid", loaderId + "");
        RequestParams params = new RequestParams(map);
        Request request = CommonRequest.createPostRequest(URL.getGiveUpUseLoaderUrl(), params);
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                try {
                    JSONObject jsonObject = new JSONObject(responseObj.toString());
                    int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
                    if (status == 1) {
                        mListener.onRefreshData(1);
                    }
                } catch (JSONException e) {
                    Log.d(TAG, "Json error");
                    e.printStackTrace();
                } catch (Exception e) {
                    Log.d(TAG, "Json to bean error");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                Log.d(TAG, "no use loader");
            }
        }));

    }
    @Override
    public void refreshUI() {
        if (loaderUseList != null && !loaderUseList.isEmpty()) {
            if (mPage > 1) {
                mListener.onLoadMoreData(loaderUseList);
            } else {
                mListener.onRefreshData(loaderUseList);
            }
        }
    }
}
